package KatarinaBot;

import org.jibble.pircbot.*;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class KatarinaBot extends PircBot {
    
	/******************
	 * 
	 * Global variables
	 *
	 ******************/
	static Random randomGenerator = new Random(); // Random number generator
	Database db = new Database();
	List<String> listOfUsers = new ArrayList<String>();
	String usersList = "";
	
	/*********************
	 * 
	 *  Standard functions
	 *  
	 ********************/
	// Constructor
    public KatarinaBot() throws Exception {
    	
    	// Sets the bots name
        this.setName("KatarinaBot");
        
    }
    
    // Retrieves user inputed command and returns a result
    public void onMessage(String channel, String sender,
                       String login, String hostname, String message){
    	
    	@SuppressWarnings("unused")
		int i = 0;
    	
    	// Get users list
    	for (Object user : this.getUsers(channel)) {
    		listOfUsers.add(user != null ? user.toString() : null);
    		i++;
    	}
    	
    	for (String s : listOfUsers) {
    	    usersList += s + "\t";
    	}
    	
    	// !time command
        if (message.contentEquals("!time".trim())) {
            cmdTime(channel);
        }
        
        // !invite command
        if (message.contentEquals("!invite".trim())) {
        	sendMessage(channel, "Please specify recipient.");
        } else if (message.startsWith("!invite")) {
        	cmdInvite(sender, channel, message);
        }
        
        // !steal command
        if (message.contentEquals("!steal".trim())) {
        	sendMessage(channel, "You need someone to steal from!");
        } else if (message.startsWith("!steal")) {
        	cmdSteal(sender, channel, message);
        }
        
        if (message.contentEquals("!something".trim())) {
        	sendMessage(channel, "Something the matter?");
        }
        
        if (message.contentEquals("!botkick".trim())) {
        	sendMessage(channel, "Who do you want to kick?");
        } else if (message.startsWith("!botkick")) {
			cmdBotKick(sender, channel, message);
        }
        
        /*
         * Admin Only commands
         */
        if (message.startsWith("+steal")) {
        	if (listOfUsers.contains("!" + sender)) {
            	cmdStealAddItem(sender, channel, message);
            } else {
            	sendMessage(channel, "You do not have enough privileges to use this command!");
            }

        }
            
        if (message.startsWith("-steal")) {
        	if (listOfUsers.contains("!" + sender)) {
            	cmdStealRemoveItem(sender, channel, message);
            } else {
            	sendMessage(channel, "You do not have enough privileges to use this command!");
            }
        }
        
        if (message.contentEquals("!users".trim())) {

        	sendMessage(channel, Colors.BLUE + "Users currently in the channel: "
        			+ Colors.NORMAL + usersList);
        	
        }
        
    }
    
    // Rejoins if bot is kicked from server
    public void onKick(String channel, String kickerNick, 
    		String kickerLogin, String kickerHostname,
            String recipientNick,
            String reason) {
    	
    	if (recipientNick.equalsIgnoreCase(getNick())) {
    	    joinChannel(channel);
    	}
    	
    }
    
    // Reconnects if bot disconnects to server
    public void onDisconnect() {
    	
    	while (!isConnected()) {
    	    try {
    	        reconnect();
    	        System.out.println("Bot has been successfully reconnected to server.");
    	    }
    	    catch (Exception e) {
    	        // Couldn't reconnect!
    	        // Pause for a short while...
    	    	System.out.println("Bot could not reconnect to server...retrying...");
    	    }
    	}
    	
    }
    
    /*******************
     *
     * Command functions
     * 
     *******************/
    // !time command
    public void cmdTime(String channelName) {
    	
    	String time = new java.util.Date().toString();
        sendMessage(channelName, "The local time is now " + time);
        
    }
    
    // !invite <username> command
    public void cmdInvite(String sender, String channel, String message) {
    	
    	// Declare variables
    	String inviteMessage = message;
    	String[] temp;
    	
    	temp = inviteMessage.split("\\s+"); // Remove whitespace
    	
    	try {
    		if (checkUsernameExists(channel, temp[1])) {
    			sendMessage(channel, temp[1] + " is already in the channel!");
    		} else {
    			sendInvite(temp[1], channel); // Sends invite
        	
    			// Notify channel of invitation
    			sendMessage(channel, sender + " has invited " + temp[1] + " to the channel!");
    		}
    	} catch (Exception ex) {
    		System.out.println("ERROR: Could not invite specified user.");
    	}
    	
    }
    
    // !steal <username> command
    public void cmdSteal(String sender, String channel, String message) {
    	
    	// Declare variables
    	String stealMessage = message;
    	String[] temp; // Temporary storage to retrieve username
    	String getStolenItem;
    	
    	temp = stealMessage.split("\\s+");
    	
    	try {
    		// Calculate item stolen from list
    		
    		int percentageSuccess = randomGenerator.nextInt(100) + 1;
    		
    		if (sender.equals(temp[1])) {
    			sendMessage(channel, "You can't steal from yourself, " + sender + ".");
    		} else if (temp[1].equals("KatarinaBot")) { 
    			sendMessage(channel, "You can't steal from me! =P");
    		} else if (checkUsernameExists(channel, temp[1])) {
    			sendMessage(channel, sender + " attempts to steal from " + temp[1] + "...");
        		if (percentageSuccess <= 75) {
        			getStolenItem = KatarinaBot.getRandom(Database.tempStolenItems);
            		sendMessage(channel, sender + " has stolen " + Colors.RED + getStolenItem + Colors.NORMAL + " from " + temp[1] + ".");
        		} else {
        			sendMessage(channel, sender + " attempted to steal from " + temp[1] + ", but was caught red-handed!");
        		}
    		} else {
        		sendMessage(channel, temp[1] + " is not in the channel!");
    		}  		
    		
    	} catch (Exception e) {
    		System.out.println("ERROR: Could not perform !steal command.");
    	}
    	
    }
    
    public void cmdStealAddItem(String sender, String channel, String message) {
    	
    	// Declare variables
    	String stealMessage = message;
    	String[] temp; // Temporary storage to retrieve username
    	
    	temp = stealMessage.split("\\s+");
    	
    	try {
    		db.insertNewStolenItem(temp[1]);
			sendMessage(channel, sender + " has added " + Colors.RED + temp[1]
					+ Colors.NORMAL + " to the stolen items list!");
		} catch (Exception e) {
			sendMessage(channel, "[ERROR] Could not add item to the list.");
			System.out.println("ERROR: Could not add item to database.");
		}
    	
    }
    
    public void cmdStealRemoveItem(String sender, String channel, String message) {
    	
    	// Declare variables
    	String stealMessage = message;
    	String[] temp; // Temporary storage to retrieve username
    	
    	temp = stealMessage.split("\\s+");
    	
    	try {
			db.deleteStolenItem(temp[1]);
			sendMessage(channel, sender + " has removed " + Colors.RED + temp[1]
					+ Colors.NORMAL + " from the stolen items list!");
		} catch (Exception e) {
			sendMessage(channel, "[ERROR] Unable to remove item. Does it exist?");
			System.out.println("ERROR: Could not delete item from the database.");
		}	
    }
    
    public void cmdBotKick(String sender, String channel, String message) {
    
    	// Declare variables
    	String inviteMessage = message;
    	String[] temp;
    		    	
    	temp = inviteMessage.split("\\s+"); // Remove whitespace
    	
    	try {
    		if (checkUsernameExists(channel, temp[1])) {
    			sendAction(channel, "kicks " + temp[1] + " for " + sender + "!");
    		} else {
    		sendMessage(channel, "[INFO] " + temp[1] + " is not in the channel!");
    		}
    	} catch (Exception ex) {
    		System.out.println("ERROR: Could not bot kick the user.");
    	}
    }
    
    /*********************
     * 
     * Calculative methods
     *
     *********************/
    // Checks if the username exists
    public boolean checkUsernameExists(String channel, String username) {

    		User[] users = getUsers(channel);
    		String status = "";
			for (User user : users) {
				if (username.equals(user.getNick())) {
				    status = "exists";
				}
			}
			
			if (status == "exists") {
				return true;
			} else {
				return false;
			}
    	
    }
    
    // Returns a random element from a specified array
    public static String getRandom (ArrayList<String> tempStolenItems) {
        int rnd = randomGenerator.nextInt(tempStolenItems.size());
        return tempStolenItems.get(rnd);
    }
}